package com.software.loginregister.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.software.loginregister.R;
import com.software.loginregister.adapter.CommentAdapter;
import com.software.loginregister.adapter.LikesAdapter;
import com.software.loginregister.api.CommentApi;
import com.software.loginregister.api.WorksApi;
import com.software.loginregister.entity.Comment;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.vo.UserUpdateDTO;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MyWorksDraftActivity extends AppCompatActivity {
    private static final String TAG = "MyWorksDraftActivity";

    private ImageView ivWorkDetail;
    private TextView tvUsername;
    private ImageView ivAvatar;
    private TextView tvTitle;
    private TextView etContentSummary;
    private TextView etIngredients;
    private TextView etCookingSteps;
    private TabLayout tabLayout;
    private ImageButton btnBack;
    private RecyclerView rvComments;
    private RecyclerView rvLikes;
    private CommentAdapter commentAdapter;
    private EditText commentInput;
    private Button commentButton;
    private Long currentUserId;
    private Long worksId;
    private CommentApi commentApi;
    private WorksApi worksApi;
    private LikesAdapter likesAdapter;

    private boolean isActivityActive = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_my_works_draft);

        // 初始化 API
        initApi();


        // 1. 先初始化视图
        initViews();

        // 2. 初始化用户信息
        UserUpdateDTO userInfo = SharedPreferencesUtil.getUserInfo(this);
        if (userInfo != null) {
            currentUserId = userInfo.getUserId();
            Log.d(TAG, "onCreate: currentUserId = " + currentUserId);
        } else {
            Log.w(TAG, "onCreate: userInfo is null");
        }

        // 3. 初始化评论API
        commentApi = RetrofitClient.getInstance().create(CommentApi.class);

        // 4. 处理Intent数据
        Intent intent = getIntent();
        if (intent != null) {
            // 添加详细的日志和错误处理
            try {
                String workId = intent.getStringExtra("workId");
                Log.d(TAG, "onCreate: Received workId from intent: " + workId);

                if (workId != null && !workId.isEmpty()) {
                    worksId = Long.parseLong(workId);
                    Log.d(TAG, "onCreate: Parsed worksId = " + worksId);
                } else {
                    Log.e(TAG, "onCreate: workId is null or empty in intent");
                    // 可以显示错误提示并结束活动
                    Toast.makeText(this, "作品ID无效", Toast.LENGTH_SHORT).show();
                    finish();
                    return;
                }

                // 其他数据获取和设置
                setData(workId,
                        intent.getStringExtra("title"),
                        intent.getStringExtra("content"),
                        intent.getStringExtra("ingredients"),
                        intent.getStringExtra("steps"),
                        intent.getStringExtra("imageUrl"),
                        intent.getStringExtra("nickname"),
                        intent.getStringExtra("avatarUrl"),
                        intent.getIntExtra("likeCount", 0),
                        intent.getIntExtra("commentCount", 0));

            } catch (NumberFormatException e) {
                Log.e(TAG, "onCreate: Error parsing workId", e);
                Toast.makeText(this, "作品ID格式错误", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
        } else {
            Log.e(TAG, "onCreate: Intent is null");
            Toast.makeText(this, "参数错误", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 5. 最后初始化评论部分
        if (worksId != null) {
            initCommentSection();
        } else {
            Log.e(TAG, "onCreate: worksId is still null after initialization");
        }

        btnBack.setOnClickListener(v -> finish());
        setupTabLayout();
    }
    private void initApi() {
        try {
            worksApi = RetrofitClient.getInstance().create(WorksApi.class);
            Log.d(TAG, "initApi: WorksApi initialized successfully");
        } catch (Exception e) {
            Log.e(TAG, "initApi: Failed to initialize WorksApi", e);
            Toast.makeText(this, "初始化失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }
    private void initViews() {
        Log.d(TAG, "initViews: Starting view initialization");

        ivWorkDetail = findViewById(R.id.iv_work_detail);
        tvUsername = findViewById(R.id.MyWorks_usernameText);
        ivAvatar = findViewById(R.id.MyWorks_avatarImage);
        tvTitle = findViewById(R.id.titleText);
        etContentSummary = findViewById(R.id.MyWorks_contentSummary);
        etIngredients = findViewById(R.id.MyWorks_ingredients);
        etCookingSteps = findViewById(R.id.MyWorks_cooking_Steps);
        tabLayout = findViewById(R.id.tabLayout);
        btnBack = findViewById(R.id.backButton);

        // 检查评论相关视图
        rvComments = findViewById(R.id.rv_comments);
        if (rvComments == null) {
            Log.e(TAG, "initViews: rv_comments not found in layout");
        }

        rvLikes = findViewById(R.id.rv_likes);
        if (rvLikes != null) {
            rvLikes.setLayoutManager(new LinearLayoutManager(this));
            // 先不创建适配器，等有数据时再创建
            Log.d(TAG, "RecyclerView initialized");
        } else {
            Log.e(TAG, "Failed to find RecyclerView");
        }

        commentInput = findViewById(R.id.MyWorks_commentInput);
        commentButton = findViewById(R.id.MyWorks_commentButton);

        Log.d(TAG, "initViews: View initialization completed");
    }


    private void setData(String workId, String title, String content,
                         String ingredients, String steps, String imageUrl,
                         String nickname, String avatarUrl,
                         int likeCount, int commentCount) {
        // 再次确保 worksId 被正确设置
        if (workId != null && !workId.isEmpty()) {
            try {
                this.worksId = Long.parseLong(workId);
                Log.d(TAG, "setData: Set worksId = " + this.worksId);
            } catch (NumberFormatException e) {
                Log.e(TAG, "setData: Error parsing workId", e);
            }
        }
        tvTitle.setText(title);
        tvUsername.setText(nickname);
        etContentSummary.setText(content);
        etIngredients.setText(ingredients);
        etCookingSteps.setText(steps);

        // 加载作品图片
        if (imageUrl != null && !imageUrl.isEmpty()) {
            Glide.with(this)
                    .load(imageUrl)
                    .placeholder(R.drawable.bg_weight_loss1)
                    .into(ivWorkDetail);
        }

        // 加载头像
        if (avatarUrl != null && !avatarUrl.isEmpty()) {
            Glide.with(this)
                    .load(avatarUrl)
                    .placeholder(R.drawable.ic_defalut_avater)
                    .circleCrop()
                    .into(ivAvatar);
        }

        // 设置互动数据
        // TODO: 在对应的Tab中显示点赞数和评论数
    }

    private void setupTabLayout() {
        // 添加标签页
        tabLayout.addTab(tabLayout.newTab().setText("评论"));
        tabLayout.addTab(tabLayout.newTab().setText("点赞"));
        // 默认显示评论列表
        rvComments.setVisibility(View.VISIBLE);
        rvLikes.setVisibility(View.GONE);
        // 设置标签页选择监听
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0: // 评论标签
                        rvComments.setVisibility(View.VISIBLE);
                        rvLikes.setVisibility(View.GONE);
                        break;
                    case 1: // 点赞标签
                        rvComments.setVisibility(View.GONE);
                        rvLikes.setVisibility(View.VISIBLE);
                        loadLikes(); // 加载点赞列表
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }

    // 添加加载点赞列表的方法
    private void loadLikes() {
        Log.d(TAG, "loadLikes: Starting to load likes");

        if (worksId == null) {
            Log.e(TAG, "loadLikes: worksId is null");
            return;
        }

        if (worksApi == null) {
            Log.e(TAG, "loadLikes: worksApi is not initialized");
            return;
        }

        Log.d(TAG, "loadLikes: Calling API for worksId = " + worksId);
        worksApi.getLikes(worksId).enqueue(new Callback<Result<Map<String, Object>>>() {
            @Override
            public void onResponse(Call<Result<Map<String, Object>>> call,
                                   Response<Result<Map<String, Object>>> response) {
                Log.d(TAG, "onResponse: Response received");

                if (!response.isSuccessful()) {
                    Log.e(TAG, "onResponse: Response not successful. Code: " + response.code());
                    return;
                }

                Result<Map<String, Object>> result = response.body();
                if (result == null) {
                    Log.e(TAG, "onResponse: Response body is null");
                    return;
                }

                Log.d(TAG, "onResponse: Result code = " + result.getCode());
                if (result.getCode() == 1 && result.getData() != null) {
                    Map<String, Object> data = result.getData();
                    int total = ((Number) data.get("total")).intValue();
                    List<Map<String, Object>> likes = (List<Map<String, Object>>) data.get("likes");

                    Log.d(TAG, "onResponse: Received " + total + " likes");
                    updateLikesUI(total, likes);
                } else {
                    Log.e(TAG, "onResponse: Invalid result code or data");
                }
            }

            @Override
            public void onFailure(Call<Result<Map<String, Object>>> call, Throwable t) {
                Log.e(TAG, "onFailure: API call failed", t);
                Toast.makeText(MyWorksDraftActivity.this,
                        "加载点赞列表失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void updateLikesUI(int total, List<Map<String, Object>> likes) {
        if (!isActivityActive) {
            Log.d(TAG, "Activity is not active, skipping UI update");
            return;
        }


        runOnUiThread(() -> {
            try {
                Log.d(TAG, "Updating UI with " + total + " likes");

                // 更新标签显示
                TabLayout.Tab likeTab = tabLayout.getTabAt(1);
                if (likeTab != null) {
                    likeTab.setText("点赞 " + total);
                    Log.d(TAG, "Updated tab text");
                }

                // 更新列表
                if (rvLikes != null) {
                    if (likesAdapter == null) {
                        Log.d(TAG, "Creating new adapter");
                        likesAdapter = new LikesAdapter(this, likes);
                        rvLikes.setAdapter(likesAdapter);
                    } else {
                        Log.d(TAG, "Updating existing adapter");
                        likesAdapter.updateData(likes);
                    }
                } else {
                    Log.e(TAG, "RecyclerView is null");
                }
            } catch (Exception e) {
                Log.e(TAG, "Error updating UI", e);
            }
        });
    }


    private void initCommentSection() {
        Log.d(TAG, "initCommentSection: Starting comment section initialization");

        if (rvComments == null) {
            Log.e(TAG, "initCommentSection: RecyclerView is null");
            return;
        }

        if (worksId == null) {
            Log.e(TAG, "initCommentSection: worksId is null");
            return;
        }
        try {
            rvComments.setLayoutManager(new LinearLayoutManager(this));
            commentAdapter = new CommentAdapter(this, new ArrayList<>(),
                    new CommentAdapter.OnCommentActionListener() {
                        @Override
                        public void onLikeClick(Comment comment, int position) {
                            toggleCommentLike(comment, position);
                        }

                        @Override
                        public void onUserClick(Integer userId) {
                            navigateToUserProfile(userId);
                        }
                    });
            rvComments.setAdapter(commentAdapter);
            Log.d(TAG, "initCommentSection: Comment adapter set successfully");
        } catch (Exception e) {
            Log.e(TAG, "initCommentSection: Error setting up RecyclerView", e);
        }

        loadComments();
    }

    private void loadComments() {
        Log.d(TAG, "loadComments: Attempting to load comments");

        if (worksId == null) {
            Log.e(TAG, "loadComments: worksId is null");
            return;
        }

        Log.d(TAG, "loadComments: Loading comments for worksId = " + worksId);

        commentApi.getComments(worksId)
                .enqueue(new Callback<Result<List<Comment>>>() {
                    @Override
                    public void onResponse(Call<Result<List<Comment>>> call,
                                           Response<Result<List<Comment>>> response) {
                        if (response.isSuccessful()) {
                            Log.d(TAG, "loadComments: Response successful");
                            Result<List<Comment>> result = response.body();
                            if (result != null && result.getCode() == 1) {
                                List<Comment> comments = result.getData();
                                Log.d(TAG, "loadComments: Loaded " +
                                        (comments != null ? comments.size() : 0) + " comments");
                                commentAdapter.setComments(comments);
                            } else {
                                Log.e(TAG, "loadComments: Invalid response code or null result");
                            }
                        } else {
                            Log.e(TAG, "loadComments: Response not successful. Code: "
                                    + response.code());
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<List<Comment>>> call, Throwable t) {
                        Log.e(TAG, "loadComments: Network request failed", t);
                    }
                });
    }



    private void postComment(String content) {
        if (currentUserId == null || worksId == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        Comment comment = new Comment();
        comment.setUserId(currentUserId.intValue());
        comment.setWorksId(worksId.intValue());
        comment.setContent(content);

        commentApi.postComment(comment)
                .enqueue(new Callback<Result<Comment>>() {
                    @Override
                    public void onResponse(Call<Result<Comment>> call,
                                           Response<Result<Comment>> response) {
                        if (response.isSuccessful() && response.body() != null
                                && response.body().getCode() == 1) {
                            Comment newComment = response.body().getData();
                            commentAdapter.addComment(newComment);
                            commentInput.setText("");
                            Toast.makeText(MyWorksDraftActivity.this,
                                    "评论成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MyWorksDraftActivity.this,
                                    "评论失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Comment>> call, Throwable t) {
                        Toast.makeText(MyWorksDraftActivity.this,
                                "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void toggleCommentLike(Comment comment, int position) {
        if (currentUserId == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        commentApi.toggleCommentLike(comment.getCommentId(), currentUserId.intValue())
                .enqueue(new Callback<Result<Map<String, Object>>>() {
                    @Override
                    public void onResponse(Call<Result<Map<String, Object>>> call,
                                           Response<Result<Map<String, Object>>> response) {
                        if (response.isSuccessful() && response.body() != null
                                && response.body().getCode() == 1) {
                            Map<String, Object> data = response.body().getData();
                            comment.setLikesCount(((Number) data.get("likesCount")).intValue());
                            commentAdapter.updateComment(comment, position);
                        } else {
                            Toast.makeText(MyWorksDraftActivity.this,
                                    "操作失败", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<Map<String, Object>>> call, Throwable t) {
                        Toast.makeText(MyWorksDraftActivity.this,
                                "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void navigateToUserProfile(Integer userId) {
        // 实现跳转到用户主页的逻辑
        Toast.makeText(this, "跳转到用户ID为 " + userId + " 的主页",
                Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: Activity is pausing");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: Activity is stopping");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: Activity is being destroyed");

        // 清理资源
        if (rvComments != null) {
            rvComments.setAdapter(null);
        }

        // 取消所有未完成的网络请求
        if (commentApi != null) {
            // 如果有未完成的请求，取消它们
        }
    }
}